package com.javacoo.xservice.base.filter.csrf;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * CsrfFilter工厂
 * <li></li>
 *
 * @author: duanyong@jccfc.com
 * @since: 2021/3/17 16:00
 */
@Component
@ConditionalOnBean(CSRFFilterConfig.class)
public class CsrfFilterFactory {
    /** CSRF过滤器配置 */
    @Autowired
    private CSRFFilterConfig csrfFilterConfig;


    @Bean
    public FilterRegistrationBean<CsrfFilter> csrfFilterRegistration(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(csrfFilter());
        registrationBean.addUrlPatterns(StringUtils.split(csrfFilterConfig.getUrlPatterns(),","));
        registrationBean.setName("CsrfFilter");
        registrationBean.setOrder(9999);
        Map<String,String> initParameters = new HashMap<>();
        initParameters.put("excludes",csrfFilterConfig.getExcludes());
        initParameters.put("enabled",csrfFilterConfig.getEnabled());
        registrationBean.setInitParameters(initParameters);
        return registrationBean;
    }
    @Bean(name = "CsrfFilter")
    public CsrfFilter csrfFilter() {
        return new CsrfFilter();
    }
}
